<?php
class MY_Controller extends CI_Controller
{
    function _admin_remap($method, $params = array())
    {
        header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
        header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
        $this->load->model('Ci_sessions');
        if ($this->session->userdata('logged_in') || ($this->input->get_post('PHPSESSID') && $this->Ci_sessions->check_exist($this->input->get_post('PHPSESSID')))) {
            if (method_exists($this, $method)) {
                return call_user_func_array(array($this, $method), $params);
            }
            show_404();
        } else {
            if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                echo '<script>window.document.location = "' . base_url() . 'admin/";</script>';
            } else {
                return call_user_func_array(array($this, 'login'), array('method' => $method, 'params' => $params));
            }
        }
//           return call_user_func_array(array($this, $method), $params);
    }

    function login($method = 'index', $params = array())
    {
        $data = array();
        header('Location:' . base_url() . 'admin/' . strtolower(get_class($this)) . '/' . $method . '/' . implode('/', $params));
        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            if ($this->input->post('captcha_input') && strtolower($this->input->post('captcha_input')) == strtolower($this->session->userdata('captcha_word'))) {
                $this->load->model('User');
                $result = $this->User->authentication($this->input->post('username'), $this->input->post('password'));
                if ($result) {
                    //Destroy old session
                    $this->session->sess_destroy();

                    //Create a fresh, brand new session
                    $this->session->sess_create();
                    //Set session data
                    $this->session->set_userdata($result);
                    header('Location:' . base_url() . 'admin/' . strtolower(get_class($this)) . '/' . $method . '/' . implode('/', $params));
                    //return call_user_func_array(array($this, $method),$params);
                } else
                    $data['message'] = 'Your username or password is not correct';
            } else    $data['message'] = 'Capcha is not correct';
        }
        $this->load->helper('captcha');

        $vals = array(
            'word' => $this->genRandomString(),
            'img_path' => getcwd() . '/public/captcha/',
            'img_url' => base_url() . 'public/captcha/',
            'font_path' => getcwd() . '/public/fonts/captcha2.ttf',
            'img_width' => '125',
            'img_height' => 80,
            'expiration' => 7200
        );

        $cap = create_captcha($vals);
        $data['captcha'] = $cap;
        $this->session->set_userdata('captcha_word', $cap['word']);
        $this->load->view('admin/login', $data);
    }

    function logout()
    {
        //Destroy session
        $this->session->sess_destroy();
        header('Location: ' . base_url() . 'admin');
    }

    function changepass()
    {
        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            try {
                $data = $_POST;
                $this->load->model('User');
                $this->User->update($data, $data['id']);
                echo json_encode(array('success' => true));
            } catch (Exception $e) {
                echo json_encode(array('success' => false));
            }
        } else echo json_encode(array('success' => false));
    }

    function genRandomString()
    {
        $length = 4;
        $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $randStr = '';

        for ($p = 0; $p < $length; $p++) {
            $randStr .= $characters[rand(0, (strlen($characters)) - 1)];
        }

        return $randStr;
    }

    function _setLayout($view_name, $layoutname, $data = array())
    {
        $main_content = $this->load->view($view_name, (!empty($data)) ? $data : null, true);
        $data['main_content'] = $main_content;
        $data['controller_name'] = get_class($this);
        $this->load->view('layout/' . $layoutname, $data);
    }

    function _dayFormat($time)
    {
        $arrTime = explode('/', $time);
        $date = date_create("{$arrTime[2]}-{$arrTime[1]}-{$arrTime[0]}");
        return date_format($date, 'Y-m-d');
    }

    function _timeFormat($time)
    {
        $arrTime = explode(' ', $time);
        $arrDate = explode('/', $arrTime[0]);
        $date = date_create("{$arrDate[2]}-{$arrDate[1]}-{$arrDate[0]} {$arrTime[1]}");
        return date_format($date, 'Y-m-d H:i:s');
    }

    function _visitorCounter()
    {
        $rip = $_SERVER['REMOTE_ADDR'];
        $sd = time();
        $count = 1;
        $maxu = 1;

        $file1 = getcwd() . '/ip.txt';
        $lines = file($file1);
        $line2 = "";

        foreach ($lines as $line_num => $line) {
            if ($line_num == 0) {
                $maxu = $line;
            } else {
                //echo $line."<br>";
                $fp = strpos($line, '****');
                $nam = substr($line, 0, $fp);
                $sp = strpos($line, '++++');
                $val = substr($line, $fp + 4, $sp - ($fp + 4));
                $diff = $sd - $val;

                if ($diff < 300 && $nam != $rip) {
                    $count = $count + 1;
                    $line2 = $line2 . $line;
                    //echo $line2;
                }
            }
        }

        $my = $rip . "****" . $sd . "++++\n";
        if ($count > $maxu)
            $maxu = $count;

        $open1 = fopen($file1, "w");
        fwrite($open1, "$maxu\n");
        fwrite($open1, "$line2");
        fwrite($open1, "$my");
        fclose($open1);
        //tang count va maxu len cho nhieu
        $count = $count;
        $maxu = $maxu;

        return $count;
    }

    function _totalVisitors()
    {
        $this->load->helper('cookie');
        $dataStr = intval(file_get_contents(getcwd() . '/counter.txt'));
        if (!get_cookie('counter') || ($_SERVER['REMOTE_ADDR'] != get_cookie('counter'))) {
            $cookie = array(
                'name' => 'counter',
                'value' => $_SERVER['REMOTE_ADDR'],
                'expire' => '900'
            );
            set_cookie($cookie);
            $dataStr += 1;
            $open1 = fopen(getcwd() . '/counter.txt', "w");
            fwrite($open1, $dataStr);
            fclose($open1);

        }
        return $dataStr;
    }
}